package com.org.android.diary.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.util.Log;

import com.org.android.diary.utils.LogUtil;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;

public class RecordService extends Service {

    private MediaRecorder recorder;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private String fileName,filePath;
    @SuppressLint("SdCardPath")
    @Override
    public void onCreate() {
        if (recorder == null)
            recorder = new MediaRecorder();
        try {
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 设置麦克风
            recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            fileName = DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".m4a";
            File destDir = new File(Environment.getExternalStorageDirectory()+"/test/");
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            filePath =  Environment.getExternalStorageDirectory()+"/test/"+ fileName;
            recorder.setOutputFile(filePath);

            LogUtil.e("输出路径-->"+ filePath);

            recorder.prepare();
            recorder.start();
        } catch (IllegalStateException e) {
            Log.i("failed!" , e.getMessage());
        } catch (IOException e) {
            Log.i("failed!" ,e.getMessage());
        }
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        recorder.stop();//停止录音
        recorder.release();//释放
        recorder = null;
        super.onDestroy();
    }
}
